﻿var httpDelete;
var httpGet;
var httpPut;

function loadXMLHttpRequest()
{
    http = null;
    if (window.XMLHttpRequest) // code for Mozilla, etc.
    {
        http = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) // code for IE
    {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return http;
}

function deleteResource(uri)
{
    httpDelete = loadXMLHttpRequest();
    
    if (httpDelete != null)
    {
        try
        {
            httpDelete.open("DELETE", uri, false);
            httpDelete.send(null);
        }
        catch (e)
        {
            // alert(e.message);
        }
    
        window.location.href = uri;
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
}

function putResource(uri)
{
    httpPut = loadXMLHttpRequest();
    
    if (httpPut != null)
    {
        try
        {
            httpPut.open("PUT", uri, false);
            httpPut.setRequestHeader("Content-Type", "text/plain");
            httpPut.send(document.getElementById("body").value);
        }
        catch (e)
        {
            // alert(e.message);
        }
    
        window.location.href = uri;
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
}

function getResource(uri)
{
    httpGet = loadXMLHttpRequest();
    
    if (http != null)
    {
        try
        {
            httpGet.onreadystatechange = getResourceText;
            httpGet.open("GET", uri, true);
            httpGet.setRequestHeader("Accept", "text/plain");
            httpGet.send(null);
        }
        catch (e)
        {
            // alert(e.message);
        }
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
}

function getResourceText()
{
    if (httpGet.readyState==4) // "loaded"
    {
        if (httpGet.status==200) // OK
        {
            var body = document.getElementById("body");
            body.innerHTML = httpGet.responseText;
        }
    }
}

function displayEdit(uri)
{
    var edit = document.getElementById("edit");
    edit.innerHTML = '<div><textarea id="body" name="body" tabindex="1" accesskey="b" rows="25" cols="80" title="Enter the page body [alt-b]"></textarea></div><div><a id="save" href="#" rel="nofollow">Save Changes</a></div>';
    
    getResource(uri);
    
    var save = document.getElementById("save");
    save.onclick = function() { putResource(uri) };
}